<template>
  <view class="normal-login-container">
    <view class="statusBox">{{
      statusArr.find((item) => item.id === status) &&
      statusArr.find((item) => item.id === status).label
    }}</view>
    <view class="detail-form-content">
      <view class="input-item">
        <view class="input-label font-34">设备名称</view>
        <text>{{ detailObj.name || "-" }}</text>
      </view>
      <view class="input-item">
        <view class="input-label font-34">设备分类</view>
        <text>{{ detailObj.deviceCategory || "-" }}</text>
      </view>
      <view class="input-item">
        <view class="input-label font-34">设备仓库</view>
        <text>{{ detailObj.warehouse || "-" }}</text>
      </view>
      <template v-if="status == 201 || status == 202">
        <view class="input-item" v-if="detailObj.applyName">
          <view class="input-label font-34">报修人</view>
          <text>{{ detailObj.applyName || "-" }}</text>
        </view>
        <view class="input-item" v-if="detailObj.applyTime">
          <view class="input-label font-34">报修时间</view>
          <text>{{ detailObj.applyTime || "-" }}</text>
        </view>
        <view class="input-item" v-if="detailObj.applyRemark">
          <view class="input-label font-34">报修描述</view>
          <text>{{ detailObj.applyRemark || "-" }}</text>
        </view>
        <view
          class="input-item"
          v-if="detailObj.applyImage && detailObj.applyImage.length > 0"
        >
          <view class="input-label font-34">报修照片</view>
          <text>
            <u-album :urls="detailObj.applyImage" keyName="src2"></u-album>
          </text>
        </view>
      </template>
      <template v-if="status == 301 || status == 302">
        <view class="input-item" v-if="detailObj.applyName">
          <view class="input-label font-34">出借人</view>
          <text>{{ detailObj.applyName || "-" }}</text>
        </view>
        <view class="input-item" v-if="detailObj.applyTime">
          <view class="input-label font-34">出借时间</view>
          <text>{{ detailObj.applyTime || "-" }}</text>
        </view>
        <view class="input-item" v-if="detailObj.planTime">
          <view class="input-label font-34">预计归还时间</view>
          <text>{{ detailObj.planTime || "-" }}</text>
        </view>
        <view class="input-item" v-if="detailObj.applyRemark">
          <view class="input-label font-34">出借描述</view>
          <text>{{ detailObj.applyRemark || "-" }}</text>
        </view>
        <view
          class="input-item"
          v-if="detailObj.applyImage && detailObj.applyImage.length > 0"
        >
          <view class="input-label font-34">出借照片</view>
          <text>
            <u-album :urls="detailObj.applyImage" keyName="src2"></u-album>
          </text>
        </view>
      </template>
      <view
        class="input-item"
        v-if="[1, 4, 5].includes(parseInt(query.repairType))"
      >
        <view class="input-label font-34">{{ timeText }}</view>
        <view @click="!disabledFalg && (timeShow = true)">{{
          searchObj.time
            ? timeFormat(searchObj.time, "yyyy年mm月dd日")
            : `请选择${timeText}`
        }}</view>
        <u-datetime-picker
          :show="timeShow"
          v-model="searchObj.time"
          :minDate="minDate"
          :maxDate="maxDate"
          mode="date"
          @confirm="timeShow = false"
          @cancel="timeShow = false"
        ></u-datetime-picker>
      </view>
      <view class="input-item" v-if="parseInt(query.repairType) === 4">
        <view class="input-label font-34">出借类型</view>
        <u-picker
          :show="typeShow"
          keyName="label"
          :columns="lendTypeList"
          @cancel="typeShow = false"
          @confirm="bindPickerChange($event, 'lendType', 'typeShow')"
        ></u-picker>
        <text @click="!disabledFalg && (typeShow = true)">{{
          (searchObj.lendType && searchObj.lendType.label) || "请选择出借类型"
        }}</text>
      </view>
      <view class="input-item" v-if="parseInt(query.repairType) === 4">
        <view class="input-label font-34">{{
          searchObj.lendType && searchObj.lendType.id === 2
            ? "出借部门"
            : "出借人"
        }}</view>
        <!-- 出借人 -->
        <u-popup :show="lendManShow">
          <view
            class="popup-box"
            :closeOnClickOverlay="true"
            @close="lendManShow = false"
          >
            <u-search
              placeholder="请输入出借人"
              @search="getlendUserListFn"
              @custom="getlendUserListFn"
              :clearabled="false"
            ></u-search>
            <view class="lendManValue">
              <u-empty v-if="lendManList === 0" mode="data" />
              <view
                class="lendManItem"
                v-for="(item, index) in lendManList"
                :key="index"
                @click="savelendMan(item)"
                >{{ item.lable }}</view
              >
            </view>
          </view>
        </u-popup>
        <!-- 出借部门 -->
        <u-picker
          :show="departmentShow"
          keyName="title"
          ref="uPicker"
          :columns="departmentList"
          @confirm="confirm"
          @cancel="departmentShow = false"
          @change="changeHandler"
        ></u-picker>
        <text @click="!disabledFalg && setShowFn()">{{ lendTxt }}</text>
      </view>
      <view class="input-item">
        <view class="input-label font-34">{{ query.title }}描述</view>
        <u--textarea
          :disabled="disabledFalg"
          v-model="searchObj.description"
          placeholder="请输入内容"
        ></u--textarea>
      </view>
      <view class="input-item">
        <view class="input-label font-34">{{ query.title }}图片</view>
        <u-upload
          :fileList="fileList1"
          @afterRead="afterRead"
          :disabled="disabledFalg"
          @delete="deletePic"
          name="1"
          multiple
          :deletable="disabledFalg ? false : true"
          :maxCount="disabledFalg ? fileList1.length : 10"
        ></u-upload>
      </view>
      <view class="submit-btn" v-if="!disabledFalg">
        <button class="cu-btn block bg-blue lg round" @click="saveDate">
          提交
        </button>
      </view>
    </view>
  </view>
</template>
    
  <script>
import { uploadFile } from "@/utils/uploadFile";
import { mapState } from "vuex";
import { getDetailTwo, getDetail } from "@/api/system/equipmentDetail.js";
import { toast } from "@/utils/common";
import {
  addAssets,
  getlendUserList,
  getDepartment,
  getEditDetailFn,
  updateAssets,
} from "@/api/system/reportForRepair.js";
export default {
  data() {
    // 归还  当前时间以后
    // 保养， 当前时间之前
    // 出借周期 当前时间以后
    return {
      timeShow: false,
      query: {},
      detailObj: {},
      searchObj: {
        name: "", //设备名称
        classification: 0, //设备分类
        warehouse: 0, //设备仓库
        description: "", //描述
        period: [], //出借周期
        time: new Date() - 1, //保养时间
        lendType: {},
        lendMan: undefined,
        // department: [],
      },
      fileList1: [],
      timeFormat: uni.$u.timeFormat,
      typeShow: false,
      lendManShow: false,
      departmentShow: false,
      lendTypeList: [
        [
          {
            label: "按人出借",
            id: 1,
          },
          {
            label: "按部门出借",
            id: 2,
          },
        ],
      ],
      lendManList: [],
      departmentList: [],
      status: null,
    };
  },
  onLoad: function (option) {
    // 设备名称 name
    // 设备分类 destroyName
    // 仓库warehouse

    // //保养时间改为保养到期时间
    // // 出借周期是时间点，结束时间
    // {
    //   assetId:id,
    //   id:id,
    //   image:[],
    //   operateType:12345,//维修租借
    //   planTime:
    // }
    this.query = option || {};
    uni.setNavigationBarTitle({ title: option.title });
  },
  computed: {
    ...mapState("user", ["statusArr"]),
    disabledFalg() {
      if (
        this.query.flag === "edit" &&
        ![201, 301].includes(parseInt(this.status))
      ) {
        return true;
      } else {
        return false;
      }
    },
    minDate() {
      if (this.query.repairType == 4 || this.query.repairType == 5) {
        return new Date() - 0;
      }
    },
    maxDate() {
      if (this.query.repairType == 1) {
        return new Date() - 0;
      }
    },
    lendTxt() {
      // if (this.searchObj?.lendType?.id === 1 && this.searchObj?.lendMan) {
      //   return this.searchObj?.lendMan?.lable;
      // } else if (
      //   this.searchObj.lendType?.id === 2 &&
      //   this.searchObj?.department
      // ) {
      //   return this.searchObj?.department?.map((item) => item?.title).join(" ");
      // } else {
      //   return "请选择";
      // }
      if (this.searchObj?.lendMan) {
        return this.searchObj?.lendMan?.lable;
      } else {
        return "请选择";
      }
    },
    timeText() {
      let num = parseInt(this.query.repairType);
      if (num === 1) {
        return "保养时间";
      } else if (num === 4) {
        return "出借周期";
      } else if (num === 5) {
        return "归还时间";
      }
      return "-";
    },
  },
  created() {
    console.log(this.query);
    if (this.query.flag === "edit") {
      this.getEditDetailFn();
    } else {
      this.getDetailFn();
    }
    this.getlendUserListFn();
    this.getDepartmentFn();
  },
  methods: {
    getEditDetailFn() {
      getEditDetailFn({ id: this.query.id }).then((res) => {
        console.log(res);
        const {
          name,
          deviceCategory,
          warehouse,
          processRemark,
          applyRemark,
          applyImage,
          planTime,
          giveType,
          giveName,
          giveId,
          healthTime,
          processTime,
          status,
          id,
          processImage,
        } = res.result;
        this.status = status;
        this.detailObj = {
          name,
          deviceCategory,
          warehouse,
          id,
          ...res.result,
        };
        this.searchObj.description = [2, 4].includes(
          parseInt(this.query.repairType)
        )
          ? applyRemark
          : processRemark;
        let imgList;
        if (this.query.repairType == 4 || this.query.repairType == 2) {
          imgList = applyImage || [];
        } else {
          imgList = processImage || [];
        }
        this.fileList1 =
          imgList?.map((item) => {
            return {
              url: item,
            };
          }) || [];
        // =======================单独针对性操作
        if (this.query.repairType == 4) {
          this.searchObj.time = planTime;
          this.searchObj.lendType =
            this.lendTypeList[0].find((item) => item.id === Number(giveType)) ||
            {};
          this.searchObj.lendMan = {
            lable: giveName,
            id: giveId,
          };
        } else if (this.query.repairType == 1) {
          this.searchObj.time = healthTime;
        } else if (this.query.repairType == 5) {
          this.searchObj.time = processTime;
        }
      });
    },
    jump(url) {
      this.$tab.navigateTo(url);
    },
    getDetailFn() {
      let fn;
      if (this.query.repairType == 4 || this.query.repairType == 2) {
        fn = getDetail;
      } else {
        fn = getDetailTwo;
      }
      fn({ id: this.query.id }).then((res) => {
        const { status } = res.result;
        this.status = status;
        this.detailObj = res.result || {};
      });
    },
    bindPickerChange(e, str, falg) {
      this.searchObj.lendMan = undefined;
      this.searchObj[str] = e.value[0];
      this[falg] = false;
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await uploadFile(lists[i].url).catch((err) => {
          return null;
        });
        if (result) {
          let item = this[`fileList${event.name}`][fileListLen];
          this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
          );
          fileListLen++;
        } else {
          this[`fileList${event.name}`].splice(fileListLen, 1);
        }
      }
    },
    saveDate() {
      //报修和出借和保养传id,归还和维修传assetId

      // let assetId = [2, 4, 1].includes(parseInt(this.query.repairType))
      //   ? this.detailObj.id
      //   : this.detailObj.assetId;
      console.log("assetId", this.detailObj);
      let param = {
        // assetId,
        id: this.detailObj.id,
        operateType: this.query.repairType,
        remark: this.searchObj.description,
        image: this.fileList1.map((item) => item.url),
        repairId: this.detailObj.repairId || undefined,
      };
      if (this.query.repairType == 1) {
        param.healthTime = this.timeFormat(this.searchObj.time, "yyyy-mm-dd");
      }
      if (this.query.repairType == 5) {
        param.planTime = this.timeFormat(this.searchObj.time, "yyyy-mm-dd");
      }
      if (this.query.repairType == 4) {
        param.planTime = this.timeFormat(this.searchObj.time, "yyyy-mm-dd");
        param.type = this.searchObj.lendType?.id;
        // if (this.searchObj.lendType?.id === 1) {
        //   param.userId = this.searchObj?.lendMan?.id;
        // }
        // if (this.searchObj.lendType?.id === 2) {
        //   param.Department = this.searchObj?.department
        //     ?.map((item) => item?.id)
        //     ?.filter((n) => n);
        // }
        param.userId = this.searchObj?.lendMan?.id;
        // if (this.searchObj.lendType?.id === 1) {
        //   param.userId = this.searchObj?.lendMan?.id;
        // }
        // if (this.searchObj.lendType?.id === 2) {
        //   param.Department = this.searchObj?.department
        //     ?.map((item) => item?.id)
        //     ?.filter((n) => n);
        // }
      }
      if (this.query.flag === "edit") {
        updateAssets(param).then((res) => {
          this.$modal.msgSuccess("操作成功");
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        });
      } else {
        addAssets(param).then((res) => {
          this.$modal.msgSuccess("操作成功");
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        });
      }
    },
    getlendUserListFn(str = "") {
      getlendUserList({ pageNumber: 1, pageSize: 50, username: str }).then(
        (res) => {
          let arr = res?.result?.records || [];
          this.lendManList = arr.map((item) => ({
            lable: item.username,
            id: item.id,
          }));
        }
      );
    },
    getDepartmentFn() {
      getDepartment({}).then((res) => {
        this.departmentList = [res.result] || [];
        this.$nextTick(() => {
          if (this.$refs.uPicker) {
            this.$refs.uPicker.setColumnValues(1, res.result[0].nodeList);
          }
        });
      });
    },
    savelendMan(item) {
      this.searchObj.lendMan = item;
      this.lendManShow = false;
    },
    setShowFn() {
      if (this.searchObj?.lendType?.id === 1) {
        this.lendManShow = true;
      } else if (this.searchObj.lendType?.id === 2) {
        this.departmentShow = true;
      } else {
        toast("请选择出借类型");
      }
    },
    changeHandler(e) {
      const {
        columnIndex,
        value,
        values, // values为当前变化列的数组内容
        index,
        // 微信小程序无法将picker实例传出来，只能通过ref操作
        picker = this.$refs.uPicker,
      } = e;
      // 当第一列值发生变化时，变化第二列(后一列)对应的选项
      if (columnIndex === 0) {
        // picker为选择器this实例，变化第二列对应的选项
        picker.setColumnValues(1, value[0].nodeList);
      }
    },
    // 回调参数为包含columnIndex、value、values
    confirm(e) {
      if (e.value && e.value?.length > 0) {
        let arr = e.value?.filter((n) => n);
        let obj = arr[arr?.length - 1];
        this.searchObj.lendMan = {
          lable: obj.title,
          id: obj.id,
        };
        this.departmentShow = false;
      }
    },
  },
};
</script>
    
  <style lang="scss">
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;
  font-weight: 700;
  .statusBox {
    padding: 20upx;
    font-size: 36upx;
    text-align: center;
    border-bottom: 1px solid #eee;
  }
  .detail-form-content {
    padding: 5% 5% calc(80upx + 5%);
    .input-item {
      margin-bottom: 14upx;
      padding: 10px 0;
      border-bottom: 1px solid #eee;
      .input-label {
        margin-bottom: 20px;
      }
      .input {
        width: 100%;
        font-size: 14px;
        font-weight: 300;
        line-height: 20px;
        text-align: left;
      }
    }
    .submit-btn {
      z-index: 999;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 0 5% 5%;
      background: #fff;
    }
  }
  .loginBottom {
    justify-content: space-between;
    padding: 30upx 0;
    font-weight: 400;
  }
  .popup-box {
    padding: 5%;
    .lendManValue {
      height: 80vh;
      overflow: auto;
      min-height: 60vh;
      max-height: 90vh;
      .lendManItem {
        border-bottom: 1px solid #eee;
        padding: 40upx;
      }
    }
  }
}
</style>
    